import { writable, readable, derived } from "svelte/store"

// 可读写的数据
export const count = writable(0)

// 仅可读的数据
export const time = readable(new Date(), function start(set) {

    const timer = setInterval(() => {
        set(new Date())
    }, 1000);

    // 最后一个订阅被销毁时调用
    return function stop() {
        clearInterval(timer)
    }
})

const start = new Date()

export const elapsed = derived(
    time,
    $time => Math.round(($time - start) / 1000)
)


// 自定义数据仓库

function createCount() {
    const { subscribe, set, update } = writable(0)
    return {
        subscribe,
        jia:() => update(n => n+1),
        jian:() => update(n => n-1),
        reset: () => set(0)
    }
}
export const count2 = createCount();


// 数据双向绑定
export const name = writable('world')

export const  greeting = derived(
    name,
    $name => `Hello ${$name}!`
)
